var app = getApp();
var url = app.globalData.url;
Page({
  data: {
    array: ["请选择",'1', '2', '3', '4'],
    //选择人数的下标，可作为人数的值
    index: 0,
    cart: {
      count: [],
      list: {},
    },
    focus: false,
    //台位号
    tableNo: 191,
    //店图
    src: '/images/touxiang.jpg',
    
    'iscart': false, //控制购物车有没有数据
    goodList: [],
    remark:"",
    checkAll: false,
    //总数量
    totalCount: 0,
    //总价格
    totalPrice: 0,
    //选择菜品件数
    cheNum: 0
  },

  bindPickerChange: function (e) {
    this.setData({
      index: e.detail.value
    })
  },

  /**
  * 删除购物车当前商品
  */
  deleteList(e) {
    const index = e.currentTarget.dataset.index;
    let goodList = this.data.goodList;
    goodList.splice(index, 1);
    this.setData({
      goodList: goodList
    });
    if (!goodList.length) {
      this.setData({
        iscart: true
      });
    } else {
      this.calculateTotal();
    }
  },

  /**
  * 计算商品总数，价格，选择菜品件数
  */
  calculateTotal: function () {
    var goodList = this.data.goodList;
    var totalCount = 0;
    var totalPrice = 0;
    var cheNum = 0;
    for (var i = 0; i < goodList.length; i++) {
      var good = goodList[i];
      if (good.checked) {
        totalCount += good.fCount;
        totalPrice += good.fCount * good.dPrice;
        cheNum ++;
      }
    }
    /**
     * 更新总数量，价格，选择的菜品件数
     */
    totalPrice = totalPrice.toFixed(2);
    this.setData({
      'totalCount': totalCount,
      'totalPrice': totalPrice,
      'cheNum' : cheNum
    })
  },

  /**
  * 用户点击商品减1
  */
  subtracttap: function (e) {
    var index = e.target.dataset.index;
    var goodList = this.data.goodList;
    var count = goodList[index].fCount;
    if (count <= 1) {
      return;
    } else {
      goodList[index].fCount--;
      this.setData({
        'goodList': goodList
      });
      this.calculateTotal();
    }
  },

  /**
  * 用户点击商品加1
  */
  addtap: function (e) {
    var index = e.target.dataset.index;
    var goodList = this.data.goodList;
    var count = goodList[index].fCount;
    goodList[index].fCount++;
    this.setData({
      'goodList': goodList
    });
    this.calculateTotal();
  },
  /**
  * 用户选择购物车商品
  */
  checkboxChange: function (e) {
    // console.log('checkbox发生change事件，携带value值为：', e.detail.value);
    var checkboxItems = this.data.goodList;
    var values = e.detail.value;
    for (var i = 0; i < checkboxItems.length; ++i) {
      checkboxItems[i].checked = false;
      for (var j = 0; j < values.length; ++j) {
        if (checkboxItems[i].dId == values[j]) {
          checkboxItems[i].checked = true;
          break;
        }
      }
    }

    var checkAll = false;
    if (checkboxItems.length == values.length) {
      checkAll = true;
    }

    this.setData({
      'goodList': checkboxItems,
      'checkAll': checkAll
    });
    this.calculateTotal();
  },


  /**
  * 用户点击全选
  */
  selectalltap: function (e) {
    // console.log('用户点击全选，携带value值为：', e.detail.value);
    var value = e.detail.value;
    var checkAll = false;
    if (value && value[0]) {
      checkAll = true;
    }

    var goodList = this.data.goodList;
    for (var i = 0; i < goodList.length; i++) {
      var good = goodList[i];
      good['checked'] = checkAll;
    }

    this.setData({
      'checkAll': checkAll,
      'goodList': goodList
    });
    this.calculateTotal();
  },

  /**
  * 生命周期函数--监听页面加载
  */
  onLoad: function (options) {
    console.log(options);
    this.hh();
    var allOrderInfo = JSON.parse(options.cart);
    var goodLists = [];
    for (var i = 0; i < allOrderInfo.length; i++) {
      for (var c in allOrderInfo[i]) {
        this.data.cart.list[i] = JSON.parse(c);
        this.data.cart.count[i] = allOrderInfo[i][c];
        var allGoods = {};
        allGoods.dId = this.data.cart.list[i].dId;
        allGoods.dName = this.data.cart.list[i].dName;
        allGoods.dPrice = this.data.cart.list[i].dPrice;
        allGoods.fCount = this.data.cart.count[i];
        allGoods.checked = false;
        goodLists.push(allGoods);
      }
      this.setData({
        goodList: goodLists
      })
    }
  },
  /**
   * 更新备注值
   */
  bindTextAreaBlur:function(e){
      this.setData({
        remark: e.detail.value
      });
      console.log(this.data.remark);
  },
  /**
   * 下单
   */
  unders:function(){
    var dishesList = [];
    var goodList = this.data.goodList;
    for(var i=0;i<goodList.length;i++){
      if (this.data.goodList[i].checked){
        var dishes = new Object();
        dishes.dId = this.data.goodList[i].dId;
        dishes.fCount = this.data.goodList[i].fCount;
        dishesList.push(dishes);
      }
    }
    var dishesStr = JSON.stringify(dishesList);
    console.log(app.globalData.uId);
    console.log(this.data.tableNo);
    console.log(this.data.index);
    console.log(this.data.remark);
    console.log(this.data.totalPrice);
    console.log(dishesStr);
    // ajax回调函数返回整个订单并跳转
    wx.request({
      url: url+'addorder.action',
      data: {
        uid: app.globalData.uId,
        tableNo: this.data.tableNo,
        pNum: this.data.index,
        remark:this.data.remark,
        totalMoney: this.data.totalPrice,
        dishesStr: dishesStr
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      method: 'post',
      success: function (res) {
        console.log(res);
        wx.navigateTo({
          // url: '/pages/detailed/detailed',
          url: '/pages/detailed/detailed?orderNo=' + res.data.data,
        })
      }
    })
    
  },

  /**
   * 画虚线
   */
  hh:function(){
    var context = wx.createContext()//创建并返回绘图上下文context对象
    context.setStrokeStyle("#1C1C1C")//设置线条的颜色
    context.setLineWidth(1)//设置线条宽度
    function drawDashLine(ctx, x1, y1, x2, y2, dashLength) {  //传context对象，始点x和y坐标，终点x和y坐标，虚线长度
      var dashLen = dashLength === undefined ? 3 : dashLength,
        xpos = x2 - x1, //得到横向的宽度;
        ypos = y2 - y1, //得到纵向的高度;
        numDashes = Math.floor(Math.sqrt(xpos * xpos + ypos * ypos) / dashLen);
      //利用正切获取斜边的长度除以虚线长度，得到要分为多少段;
      for (var i = 0; i < numDashes; i++) {
        if (i % 2 === 0) {
          ctx.moveTo(x1 + (xpos / numDashes) * i, y1 + (ypos / numDashes) * i);
          //有了横向宽度和多少段，得出每一段是多长，起点 + 每段长度 * i = 要绘制的起点；
        } else {
          ctx.lineTo(x1 + (xpos / numDashes) * i, y1 + (ypos / numDashes) * i);
        }
      }
      ctx.stroke();
    }
    drawDashLine(context, 0, 0, 400, 0, 3);//横向虚线
    //微信小程序画图
    wx.drawCanvas({
      canvasId: 'canvas',
      actions: context.getActions()
    });
  },
  /**
  * 生命周期函数--监听页面初次渲染完成
  */
  onReady: function () {
    this.calculateTotal();
  },

  /**
  * 生命周期函数--监听页面显示
  */
  onShow: function () {

  },

  /**
  * 生命周期函数--监听页面隐藏
  */
  onHide: function () {

  },

  /**
  * 生命周期函数--监听页面卸载
  */
  onUnload: function () {

  },

  /**
  * 页面相关事件处理函数--监听用户下拉动作
  */
  onPullDownRefresh: function () {

  },

  /**
  * 页面上拉触底事件的处理函数
  */
  onReachBottom: function () {

  },

  /**
  * 用户点击右上角分享
  */
  onShareAppMessage: function () {

  },


})